package net.sf.sqlparser.deparser;

import java.util.Iterator;

import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.select.FromItem;
import net.sf.jsqlparser.statement.select.Join;
import net.sf.jsqlparser.statement.select.SelectExpressionItem;
import net.sf.jsqlparser.util.deparser.SelectDeParser;

/**
 * SELECT查询解析类，继承自JSqlParser的SelectDeParser
 * @author lixiangyang
 *
 */
public class SelectParser extends SelectDeParser {
	
	public SelectParser() {
	}
	
	public SelectParser(ExpressionParser expressionVisitor, StringBuffer buffer) {
		super(expressionVisitor, buffer);
	}
	
	public void setExpressionVisitor(ExpressionParser visitor) {
		super.setExpressionVisitor(visitor);
	}
	
	// TODO
	
	/**
	 * 重写父类方法，去掉父类方法中table前的as 
	 */
	public void visit(SelectExpressionItem selectExpressionItem) {
		selectExpressionItem.getExpression().accept(expressionVisitor);
		String alias = selectExpressionItem.getAlias();
		if (alias != null && !alias.equals("")) {
			buffer.append(" " + alias);
		}
	}
	
	/**
	 * 重写父类方法，去掉父类方法中table前的as 
	 */
	public void visit(Table tableName) {
		buffer.append(tableName.getWholeTableName());
		String alias = tableName.getAlias();
		if (alias != null && !alias.equals("")) {
			buffer.append(" " + alias);
		}
	}
	
    /**
     * 重写父类方法，在JOIN之前增加空格
     */
    public void deparseJoin(Join join) {
        if (join.isSimple()) {
            buffer.append(", ");
        } else {
            buffer.append(" ");
            if (join.isRight()) {
                buffer.append("RIGHT ");
            } else if (join.isNatural()) {
                buffer.append("NATURAL ");
            } else if (join.isFull()) {
                buffer.append("FULL ");
            } else if (join.isLeft()) {
                buffer.append("LEFT ");
            }
            if (join.isOuter()) {
                buffer.append("OUTER ");
            } else if (join.isInner()) {
                buffer.append("INNER ");
            }
            buffer.append("JOIN ");
        }

        FromItem fromItem = join.getRightItem();
        fromItem.accept(this);
        if (join.getOnExpression() != null) {
            buffer.append(" ON ");
            join.getOnExpression().accept(expressionVisitor);
        }
        if (join.getUsingColumns() != null) {
            buffer.append(" USING ( ");
            for (Iterator iterator = join.getUsingColumns().iterator(); iterator.hasNext();) {
                Column column = (Column) iterator.next();
                buffer.append(column.getWholeColumnName());
                if (iterator.hasNext()) {
                    buffer.append(" ,");
                }
            }
            buffer.append(")");
        }
    }
}
